#!/usr/bin/env python3
"""
AI目录安装器 - 极简版本
1:1复制远程目录到本地，支持 .cursor、.ai、.claude 目录
零外部依赖，仅使用Python标准库
"""

import os
import sys
import argparse
import urllib.request
import urllib.error
import zipfile
import tempfile
import subprocess
import shutil
from pathlib import Path

# 配置
DEFAULT_REPO = "https://gitee.com/xkcyy/ai-code-ext"
SUPPORTED_DIRS = [".cursor", ".claude", ".ai"]

# 全局缓存目录配置
def get_project_cache_dir():
    """获取基于项目路径的唯一缓存目录"""
    current_dir = Path.cwd().resolve()

    # 将路径分隔符替换为 __，作为项目ID
    project_path_str = str(current_dir)
    # 统一替换 / 和 \ 为 __
    project_id = project_path_str.replace('/', '__').replace('\\', '__').replace(':', '__')

    # 确保项目ID不以 __ 开头或结尾
    project_id = project_id.strip('__')

    # 限制长度，避免路径过长
    if len(project_id) > 100:
        project_id = project_id[:100]

    home_dir = Path.home()
    cache_base_dir = home_dir / ".ai-code-ext-cache"
    cache_dir = cache_base_dir / project_id
    return cache_dir

def get_cache_repo_dir():
    """获取缓存中的仓库目录路径"""
    cache_dir = get_project_cache_dir()
    repo_dir = cache_dir / "repo"
    return repo_dir

def get_project_info_file():
    """获取项目信息文件路径"""
    cache_dir = get_project_cache_dir()
    info_file = cache_dir / "project-info.json"
    return info_file

def save_project_info():
    """保存项目信息到缓存"""
    current_dir = Path.cwd().resolve()
    info_file = get_project_info_file()

    # 确保缓存目录存在
    info_file.parent.mkdir(parents=True, exist_ok=True)

    project_info = {
        "project_path": str(current_dir),
        "created_time": current_dir.stat().st_mtime,
        "last_sync_time": None
    }

    import json
    with open(info_file, 'w', encoding='utf-8') as f:
        json.dump(project_info, f, indent=2, ensure_ascii=False)

def load_project_info():
    """加载项目信息"""
    info_file = get_project_info_file()
    if not info_file.exists():
        return None

    try:
        import json
        with open(info_file, 'r', encoding='utf-8') as f:
            return json.load(f)
    except:
        return None

def ensure_cache_exists():
    """确保缓存目录存在并已克隆仓库"""
    cache_dir = get_project_cache_dir()
    repo_dir = get_cache_repo_dir()

    if not cache_dir.exists():
        cache_dir.mkdir(parents=True, exist_ok=True)
        print(f"创建项目缓存目录: {cache_dir}")
        # 保存项目信息
        save_project_info()

    # 检查repo目录是否是有效的Git仓库
    repo_needs_init = False
    if not repo_dir.exists():
        repo_needs_init = True
    else:
        # 检查是否存在.git目录
        git_dir = repo_dir / ".git"
        if not git_dir.exists():
            repo_needs_init = True
            print(f"检测到repo目录不是Git仓库，将重新初始化")
            # 删除无效的repo目录
            shutil.rmtree(repo_dir, ignore_errors=True)

    if repo_needs_init:
        print("初始化项目Git缓存...")
        repo_url = "https://gitee.com/xkcyy/ai-code-ext.git"
        result = subprocess.run(['git', 'clone', repo_url, str(repo_dir)],
                              capture_output=True, text=True)
        if result.returncode != 0:
            print(f"克隆仓库到缓存失败: {result.stderr}")
            return False
        print("+ 项目Git缓存初始化完成")

    return True

def update_cache_from_remote():
    """从远程仓库更新缓存"""
    if not ensure_cache_exists():
        return False

    repo_dir = get_cache_repo_dir()
    print("更新项目缓存...")

    # 拉取最新更改
    result = subprocess.run(['git', 'pull', 'origin', 'master'],
                          cwd=repo_dir, capture_output=True, text=True)
    if result.returncode != 0:
        print(f"更新缓存失败: {result.stderr}")
        return False

    print("+ 项目缓存更新完成")
    return True

def sync_local_to_cache(local_dir, cache_dir, dir_name):
    """同步本地目录到缓存目录"""
    local_path = Path(local_dir) / dir_name
    cache_path = cache_dir / dir_name

    if not local_path.exists():
        # 本地删除了该目录，也从缓存删除
        if cache_path.exists():
            shutil.rmtree(cache_path)
            print(f"   - 从缓存删除: {dir_name}")
        return

    # 本地存在该目录，同步到缓存
    if cache_path.exists():
        shutil.rmtree(cache_path)
    shutil.copytree(local_path, cache_path)
    print(f"   + 同步到缓存: {dir_name} -> {cache_path}")

def sync_cache_to_local(cache_dir, local_dir, dir_name):
    """同步缓存目录到本地目录"""
    cache_path = cache_dir / dir_name
    local_path = Path(local_dir) / dir_name

    if not cache_path.exists():
        # 缓存中没有该目录，删除本地目录
        if local_path.exists():
            shutil.rmtree(local_path)
            print(f"   - 从本地删除: {dir_name}")
        return

    # 缓存存在该目录，同步到本地
    if local_path.exists():
        shutil.rmtree(local_path)
    shutil.copytree(cache_path, local_path)
    print(f"   + 同步到本地: {dir_name} -> {local_path}")

def show_cache_status():
    """显示缓存状态"""
    cache_dir = get_project_cache_dir()
    repo_dir = get_cache_repo_dir()
    project_info = load_project_info()

    print("项目缓存状态:")
    print("-" * 40)

    # 显示项目信息
    if project_info:
        print(f"项目路径: {project_info['project_path']}")
    else:
        print(f"项目路径: {Path.cwd().resolve()}")

    if not cache_dir.exists():
        print("缓存状态: 未初始化")
        print(f"缓存路径: {cache_dir}")
        return

    print("缓存状态: 已初始化")
    print(f"缓存路径: {cache_dir}")

    if not repo_dir.exists():
        print("仓库状态: 未克隆")
        return

    print("仓库状态: 已克隆")
    print(f"仓库路径: {repo_dir}")

    # 检查每个目录的状态
    print("\n目录内容:")
    for dir_name in SUPPORTED_DIRS:
        cache_path = repo_dir / dir_name
        if cache_path.exists():
            try:
                # 计算文件数量
                file_count = len(list(cache_path.rglob('*')))
                mtime = cache_path.stat().st_mtime
                import time
                time_str = time.strftime("%Y-%m-%d %H:%M", time.localtime(mtime))
                print(f"  {dir_name:<15} {file_count:>3} 文件  {time_str}")
            except Exception as e:
                print(f"  {dir_name:<15} 错误: {e}")
        else:
            print(f"  {dir_name:<15} 不存在")

    # 显示远程仓库状态
    try:
        result = subprocess.run(['git', 'remote', '-v'],
                              cwd=repo_dir, capture_output=True, text=True)
        if result.returncode == 0:
            print(f"\n远程仓库: {result.stdout.strip()}")
    except:
        pass

def list_all_project_caches():
    """列出所有项目的缓存"""
    home_dir = Path.home()
    cache_base_dir = home_dir / ".ai-code-ext-cache"

    if not cache_base_dir.exists():
        print("未找到任何项目缓存")
        return

    project_caches = [d for d in cache_base_dir.iterdir() if d.is_dir()]

    if not project_caches:
        print("未找到任何项目缓存")
        return

    print(f"找到 {len(project_caches)} 个项目缓存:")
    print("=" * 80)

    for project_cache in sorted(project_caches):
        info_file = project_cache / "project-info.json"
        repo_dir = project_cache / "repo"

        # 尝试从项目信息文件读取路径
        if info_file.exists():
            try:
                import json
                with open(info_file, 'r', encoding='utf-8') as f:
                    project_info = json.load(f)
                project_path = project_info.get('project_path', '未知路径')
            except:
                project_path = '读取失败'
        else:
            # 如果没有信息文件，尝试从缓存目录名还原路径
            project_id = project_cache.name
            project_path = project_id.replace('__', '/')
            # 尝试恢复盘符 (Windows)
            if '__' in project_id and len(project_id.split('__')) >= 2:
                parts = project_id.split('__')
                if parts[0].isalpha() and len(parts[0]) == 1:
                    project_path = f"{parts[0]}:/" + "/".join(parts[1:])

        status = "+ 有效" if repo_dir.exists() else "- 无效"
        print(f"缓存ID: {project_cache.name}")
        print(f"项目路径: {project_path}")
        print(f"状态: {status}")
        print("-" * 80)

def clean_cache():
    """清理当前项目的缓存"""
    cache_dir = get_project_cache_dir()

    print("清理项目缓存...")
    if not cache_dir.exists():
        print("   + 项目缓存目录不存在，无需清理")
        return

    try:
        # Windows系统可能需要多次尝试
        import time
        import atexit

        def cleanup_later():
            time.sleep(1)  # 等待1秒后清理
            try:
                shutil.rmtree(cache_dir, ignore_errors=True)
                print(f"   + 延迟清理缓存完成: {cache_dir}")
            except:
                pass

        # 注册延迟清理函数
        atexit.register(cleanup_later)

        # 尝试立即清理
        try:
            shutil.rmtree(cache_dir, ignore_errors=True)
            print(f"   + 项目缓存已清理: {cache_dir}")
        except Exception as e:
            print(f"   ! 立即清理失败，将延迟清理: {e}")
            print("   + 缓存将在程序退出后自动清理")
    except Exception as e:
        print(f"   - 清理缓存失败: {e}")

def clean_all_caches():
    """清理所有项目的缓存"""
    home_dir = Path.home()
    cache_base_dir = home_dir / ".ai-code-ext-cache"

    print("清理所有项目缓存...")

    if not cache_base_dir.exists():
        print("   + 缓存基础目录不存在")
        return

    try:
        shutil.rmtree(cache_base_dir, ignore_errors=True)
        print(f"   + 所有项目缓存已清理: {cache_base_dir}")
    except Exception as e:
        print(f"   - 清理缓存失败: {e}")

def get_target_dir(dir_name):
    """获取目标目录名"""
    return dir_name

def download_repo_zip(repo_url):
    """下载仓库ZIP"""
    zip_url = f"{repo_url}/repository/archive/main.zip"
    try:
        req = urllib.request.Request(zip_url)
        req.add_header('User-Agent', 'AI-Command-Installer/1.0')

        with urllib.request.urlopen(req, timeout=60) as response:
            if response.status == 200:
                return response.read()
            else:
                raise Exception(f"HTTP错误: {response.status}")
    except urllib.error.HTTPError as e:
        if e.code == 404:
            raise Exception(f"仓库不存在或无法访问: {zip_url}")
        else:
            raise Exception(f"HTTP错误 {e.code}: {zip_url}")
    except Exception as e:
        raise Exception(f"网络连接失败: {e}")

def extract_dir_from_zip(zip_content, source_dir, target_dir):
    """从ZIP提取指定目录"""
    file_count = 0

    with tempfile.NamedTemporaryFile(delete=False) as temp_file:
        temp_file.write(zip_content)
        temp_file.flush()

        try:
            with zipfile.ZipFile(temp_file.name, 'r') as zip_ref:
                source_prefix = f"ai-code-ext-main/{source_dir}/"

                for file_info in zip_ref.infolist():
                    if not file_info.filename.startswith(source_prefix):
                        continue

                    if file_info.is_dir():
                        continue

                    relative_path = file_info.filename[len(source_prefix):].lstrip('/')
                    if not relative_path:
                        continue

                    target_path = target_dir / relative_path
                    target_path.parent.mkdir(parents=True, exist_ok=True)

                    with zip_ref.open(file_info) as source_file:
                        with open(target_path, 'wb') as target_file:
                            target_file.write(source_file.read())

                    file_count += 1
        finally:
            os.unlink(temp_file.name)

    return file_count

def install_dir(dir_name, repo_url, force=False):
    """安装目录"""
    target_dir = Path(get_target_dir(dir_name))

    # 检查目录是否已存在
    if target_dir.exists() and not force:
        print(f"{target_dir} 目录已存在，使用 --force 强制重新安装")
        return False

    try:
        print(f"开始安装 {dir_name} 目录...")

        # 下载仓库
        print("下载仓库文件...")
        zip_content = download_repo_zip(repo_url)

        # 删除现有目录（如果force）
        if target_dir.exists() and force:
            import shutil
            shutil.rmtree(target_dir)

        # 创建目标目录
        target_dir.mkdir(parents=True, exist_ok=True)

        # 提取文件
        print(f"提取 {dir_name} 文件...")
        file_count = extract_dir_from_zip(zip_content, dir_name, target_dir)

        print(f"安装完成，共提取 {file_count} 个文件")
        print(f"√ {dir_name} 目录安装成功")
        return True

    except Exception as e:
        print(f"安装失败: {e}")
        return False

def list_dirs():
    """列出已安装目录"""
    print("已安装的目录:")
    print("-" * 30)

    found_any = False
    for dir_name in SUPPORTED_DIRS:
        target_dir = Path(dir_name)
        if target_dir.exists():
            found_any = True
            # 获取目录修改时间
            try:
                import time
                mtime = target_dir.stat().st_mtime
                time_str = time.strftime("%Y-%m-%d %H:%M", time.localtime(mtime))
                print(f"{dir_name:<15} {time_str}")
            except:
                print(f"{dir_name:<15} 未知")

    if not found_any:
        print("尚未安装任何目录")

def create_demo(dir_name):
    """创建演示版本"""
    if dir_name not in SUPPORTED_DIRS:
        print(f"不支持的目录: {dir_name}")
        return

    target_dir = Path(dir_name)
    target_dir.mkdir(parents=True, exist_ok=True)

    # 创建README
    demo_content = f"""# {dir_name} 目录演示

这是一个{dir_name}的示例目录。

## 包含内容
- README.md: 目录说明
- templates/: 模板文件目录
"""

    with open(target_dir / "README.md", 'w', encoding='utf-8') as f:
        f.write(demo_content)

    # 创建模板目录和示例文件
    templates_dir = target_dir / "templates"
    templates_dir.mkdir(exist_ok=True)

    with open(templates_dir / "example.md", 'w', encoding='utf-8') as f:
        f.write(f"# 示例模板\n\n这是一个{dir_name}的示例模板文件。")

    print(f"√ {dir_name} 演示创建成功")

def pull_from_remote():
    """从远程仓库拉取更新到本地"""
    print("AI目录安装器 - 从远程仓库拉取更新")
    print("=" * 40)

    original_cwd = os.getcwd()
    repo_dir = get_cache_repo_dir()

    try:
        # 1. 检查是否存在全局缓存
        print("1. 检查全局缓存...")
        cache_exists = ensure_cache_exists()

        if not cache_exists:
            print("   + 未找到全局缓存，正在从Gitee初始化...")
            # 缓存不存在，从远程仓库创建
            if not update_cache_from_remote():
                print("   - 从远程仓库初始化缓存失败")
                return
            print("   + 全局缓存初始化完成")
        else:
            print("   + 发现全局缓存")
            # 将本地文件覆盖到全局缓存
            print("2. 同步本地文件到全局缓存...")
            for dir_name in SUPPORTED_DIRS:
                sync_local_to_cache(original_cwd, repo_dir, dir_name)

        # 3. 从远程仓库拉取最新更新
        print("\n3. 从远程仓库拉取更新...")
        if not update_cache_from_remote():
            print("   - 拉取更新失败，使用本地缓存版本")
        else:
            print("   + 远程更新拉取成功")

        # 4. 将缓存文件同步到当前目录
        print("\n4. 同步缓存文件到当前目录...")
        for dir_name in SUPPORTED_DIRS:
            sync_cache_to_local(repo_dir, original_cwd, dir_name)

    except Exception as e:
        print(f"   - 拉取过程中发生错误: {e}")

    print("\n" + "=" * 40)
    print("+ 拉取完成！AI命令已更新到本地")
    print("+ 全局缓存目录:", get_project_cache_dir())
    print("+ 远程仓库: https://gitee.com/xkcyy/ai-code-ext")

def push_to_remote():
    """推送本地修改到远程仓库"""
    print("AI目录安装器 - 推送本地修改到远程仓库")
    print("=" * 40)

    # 检查本地是否有AI命令目录
    exported_any = False
    for dir_name in SUPPORTED_DIRS:
        source_dir = Path(dir_name)
        if source_dir.exists():
            exported_any = True
            break

    if not exported_any:
        print("   - 未找到任何已安装的AI命令目录")
        return

    original_cwd = os.getcwd()
    repo_dir = get_cache_repo_dir()

    try:
        # 1. 先执行pull操作，确保有最新版本
        print("1. 执行pull操作，获取最新版本...")
        print("   + 正在从远程仓库拉取更新...")
        if not pull_from_remote_internal():
            print("   - Pull操作失败，但继续尝试推送")
        else:
            print("   + Pull操作完成")

        # 2. 同步本地文件到缓存
        print("\n2. 同步本地AI命令到缓存...")
        for dir_name in SUPPORTED_DIRS:
            sync_local_to_cache(original_cwd, repo_dir, dir_name)

        # 3. 执行Git操作
        print("\n3. 执行Git操作...")

        # 添加文件
        result = subprocess.run(['git', 'add', '.'], cwd=repo_dir, capture_output=True, text=True)
        if result.returncode != 0:
            print(f"   - 添加文件失败: {result.stderr}")
            return
        print("   + 文件添加成功")

        # 提交变更
        try:
            result = subprocess.run(['git', 'commit', '-m', 'update AI commands'],
                                  capture_output=True, text=True, cwd=repo_dir)
            if result.returncode != 0:
                error_msg = result.stderr.strip()
                stdout_msg = result.stdout.strip()

                # 检查是否是"没有变更需要提交"的情况
                if "nothing to commit" in error_msg or "nothing added" in stdout_msg or "working tree clean" in stdout_msg:
                    print("   + 没有文件变更，无需提交")
                    print("\n推送完成！没有需要更新的文件。")
                    return

                print(f"   - Git提交错误详情: {error_msg}")
                if "Author identity unknown" in error_msg or "Please tell me who you are" in error_msg:
                    print("   - Git用户信息未配置，尝试配置...")
                    # 尝试配置Git用户信息
                    subprocess.run(['git', 'config', 'user.name', 'AI Commands Sync'], cwd=repo_dir)
                    subprocess.run(['git', 'config', 'user.email', 'ai-code-ext@sync.local'], cwd=repo_dir)

                    # 重新尝试提交
                    result = subprocess.run(['git', 'commit', '-m', 'update AI commands'],
                                          capture_output=True, text=True, cwd=repo_dir)
                    if result.returncode != 0:
                        print(f"   - 提交失败: {result.stderr}")
                        return
                    print("   + 提交成功（使用临时用户信息）")
                else:
                    print(f"   - 提交失败: {error_msg}")
                    return
            else:
                print("   + 提交成功")
        except Exception as e:
            print(f"   - 提交异常: {e}")
            return

        # 推送到远程
        print("\n4. 推送到远程仓库...")
        try:
            # 使用subprocess.run来推送，允许交互式输入用户名密码
            print("   * 可能需要输入Gitee用户名和密码")
            result = subprocess.run(['git', 'push', 'origin', 'master'],
                                  cwd=repo_dir, text=True, stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr)
            if result.returncode == 0:
                print("   + 推送成功")
            else:
                print("   - 推送失败")
                print("   * 请确保：")
                print("      - 已配置Git用户信息 (git config --global user.name/email)")
                print("      - 有仓库推送权限")
                print("      - 网络连接正常")
                return
        except Exception as e:
            print(f"   - 推送异常: {e}")
            return

        print("   + Git操作完成")

    except Exception as e:
        print(f"   - 推送过程中发生错误: {e}")

    print("\n" + "=" * 40)
    print("+ 推送完成！AI命令已更新到远程仓库")
    print("+ 项目缓存目录:", get_project_cache_dir())
    print("+ 远程仓库: https://gitee.com/xkcyy/ai-code-ext")

def pull_from_remote_internal():
    """内部pull操作，不包含环境变量更新"""
    original_cwd = os.getcwd()
    repo_dir = get_cache_repo_dir()

    try:
        # 检查是否存在全局缓存
        cache_exists = ensure_cache_exists()

        if not cache_exists:
            # 缓存不存在，从远程仓库创建
            if not update_cache_from_remote():
                return False
        else:
            # 将本地文件覆盖到全局缓存
            for dir_name in SUPPORTED_DIRS:
                sync_local_to_cache(original_cwd, repo_dir, dir_name)

        # 从远程仓库拉取最新更新
        if not update_cache_from_remote():
            return False

        # 将缓存文件同步到当前目录
        for dir_name in SUPPORTED_DIRS:
            sync_cache_to_local(repo_dir, original_cwd, dir_name)

        return True

    except Exception as e:
        print(f"   - 内部pull操作失败: {e}")
        return False

def sync_to_remote():
    """自动同步AI命令到远程仓库（使用项目缓存机制）"""
    print("AI目录安装器 - 同步命令到远程仓库")
    print("=" * 40)

    # 检查本地是否有AI命令目录
    exported_any = False
    for dir_name in SUPPORTED_DIRS:
        source_dir = Path(dir_name)
        if source_dir.exists():
            exported_any = True
            break

    if not exported_any:
        print("   - 未找到任何已安装的AI命令目录")
        return

    original_cwd = os.getcwd()
    repo_dir = get_cache_repo_dir()

    try:
        # 1. 确保项目缓存存在并更新
        print("1. 初始化项目缓存...")
        if not ensure_cache_exists():
            return

        # 2. 从远程仓库更新缓存
        print("\n2. 更新项目缓存...")
        if not update_cache_from_remote():
            print("   - 缓存更新失败，但继续使用本地缓存")
        else:
            print("   + 项目缓存已是最新版本")

        # 3. 同步本地文件到缓存
        print("\n3. 同步本地AI命令到缓存...")
        for dir_name in SUPPORTED_DIRS:
            sync_local_to_cache(original_cwd, repo_dir, dir_name)

        # 4. 执行Git操作
        print("\n4. 执行Git操作...")

        # 添加文件
        result = subprocess.run(['git', 'add', '.'], cwd=repo_dir, capture_output=True, text=True)
        if result.returncode != 0:
            print(f"   - 添加文件失败: {result.stderr}")
            return
        print("   + 文件添加成功")

        # 提交变更
        try:
            result = subprocess.run(['git', 'commit', '-m', 'update AI commands'],
                                  capture_output=True, text=True, cwd=repo_dir)
            if result.returncode != 0:
                error_msg = result.stderr.strip()
                stdout_msg = result.stdout.strip()

                # 检查是否是"没有变更需要提交"的情况
                if "nothing to commit" in error_msg or "nothing added" in stdout_msg or "working tree clean" in stdout_msg:
                    print("   + 没有文件变更，无需提交")
                    print("\n同步完成！没有需要更新的文件。")
                    return

                print(f"   - Git提交错误详情: {error_msg}")
                if "Author identity unknown" in error_msg or "Please tell me who you are" in error_msg:
                    print("   - Git用户信息未配置，尝试配置...")
                    # 尝试配置Git用户信息
                    subprocess.run(['git', 'config', 'user.name', 'AI Commands Sync'], cwd=repo_dir)
                    subprocess.run(['git', 'config', 'user.email', 'ai-code-ext@sync.local'], cwd=repo_dir)

                    # 重新尝试提交
                    result = subprocess.run(['git', 'commit', '-m', 'update AI commands'],
                                          capture_output=True, text=True, cwd=repo_dir)
                    if result.returncode != 0:
                        print(f"   - 提交失败: {result.stderr}")
                        return
                    print("   + 提交成功（使用临时用户信息）")
                else:
                    print(f"   - 提交失败: {error_msg}")
                    return
            else:
                print("   + 提交成功")
        except Exception as e:
            print(f"   - 提交异常: {e}")
            return

        # 推送到远程
        print("\n5. 推送到远程仓库...")
        try:
            # 使用subprocess.run来推送，允许交互式输入用户名密码
            print("   * 可能需要输入Gitee用户名和密码")
            result = subprocess.run(['git', 'push', 'origin', 'master'],
                                  cwd=repo_dir, text=True, stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr)
            if result.returncode == 0:
                print("   + 推送成功")
            else:
                print("   - 推送失败")
                print("   * 请确保：")
                print("      - 已配置Git用户信息 (git config --global user.name/email)")
                print("      - 有仓库推送权限")
                print("      - 网络连接正常")
                return
        except Exception as e:
            print(f"   - 推送异常: {e}")
            return

        print("   + Git操作完成")

    except Exception as e:
        print(f"   - 同步过程中发生错误: {e}")

    print("\n" + "=" * 40)
    print("+ 同步完成！AI命令已更新到远程仓库")
    print("+ 项目缓存目录:", get_project_cache_dir())
    print("+ 远程仓库: https://gitee.com/xkcyy/ai-code-ext")

    # 5. 更新applications目录的环境变量
    print("\n5. 更新applications环境变量...")
    try:
        apps_dir = Path(original_cwd) / ".ai" / "applications"
        env_manager_path = apps_dir / "env-manager.py"

        if env_manager_path.exists():
            print("   + 发现环境管理器，正在更新系统环境...")
            result = subprocess.run([
                sys.executable, str(env_manager_path), "sync", "--cwd", original_cwd
            ], capture_output=True, text=True, cwd=apps_dir)

            if result.returncode == 0:
                print("   + 环境变量更新成功")
                print(result.stdout)
            else:
                print(f"   - 环境变量更新失败: {result.stderr}")
        else:
            print("   - 未找到环境管理器，跳过环境变量更新")
    except Exception as e:
        print(f"   - 环境变量更新异常: {e}")

def main():
    """主函数"""
    parser = argparse.ArgumentParser(
        description="AI目录安装器 - 1:1复制远程目录到本地",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
示例:
  %(prog)s install --dir .cursor      # 安装.cursor目录
  %(prog)s install                    # 安装所有目录
  %(prog)s list                       # 查看已安装目录
  %(prog)s demo --dir .cursor         # 创建演示版本
  %(prog)s sync                       # 同步命令到远程仓库
        """
    )

    subparsers = parser.add_subparsers(dest='command', help='可用命令')

    # install命令
    install_parser = subparsers.add_parser('install', help='安装目录')
    install_parser.add_argument('--dir', choices=SUPPORTED_DIRS + ['all'], help='目录类型，默认安装所有')
    install_parser.add_argument('--repo', default=DEFAULT_REPO, help='Gitee仓库地址')
    install_parser.add_argument('--force', action='store_true', help='强制重新安装')

    # list命令
    subparsers.add_parser('list', help='列出已安装的目录')

    # demo命令
    demo_parser = subparsers.add_parser('demo', help='创建演示版本')
    demo_parser.add_argument('--dir', required=True, choices=SUPPORTED_DIRS, help='目录类型')

    # pull命令
    subparsers.add_parser('pull', help='从远程仓库拉取更新到本地')

    # push命令
    subparsers.add_parser('push', help='推送本地修改到远程仓库')

    # cache命令
    cache_parser = subparsers.add_parser('cache', help='管理项目缓存')
    cache_subparsers = cache_parser.add_subparsers(dest='cache_action', help='缓存操作')

    cache_subparsers.add_parser('status', help='查看当前项目缓存状态')
    cache_subparsers.add_parser('update', help='更新当前项目缓存')
    cache_subparsers.add_parser('clean', help='清理当前项目缓存')
    cache_subparsers.add_parser('list', help='列出所有项目缓存')
    cache_subparsers.add_parser('clean-all', help='清理所有项目缓存')

    args = parser.parse_args()

    if not args.command:
        parser.print_help()
        return

    try:
        if args.command == 'install':
            if args.dir and args.dir != 'all':
                install_dir(args.dir, args.repo, args.force)
            else:
                print("AI目录安装器 - 安装所有目录")
                for dir_name in SUPPORTED_DIRS:
                    install_dir(dir_name, args.repo, args.force)
        elif args.command == 'list':
            list_dirs()
        elif args.command == 'demo':
            create_demo(args.dir)
        elif args.command == 'pull':
            pull_from_remote()
        elif args.command == 'push':
            push_to_remote()
        elif args.command == 'cache':
            if args.cache_action == 'status':
                show_cache_status()
            elif args.cache_action == 'update':
                update_cache_from_remote()
            elif args.cache_action == 'clean':
                clean_cache()
            elif args.cache_action == 'list':
                list_all_project_caches()
            elif args.cache_action == 'clean-all':
                clean_all_caches()
            else:
                print("请指定缓存操作：status, update, clean, list, clean-all")
    except KeyboardInterrupt:
        print("\n操作已取消")
    except Exception as e:
        print(f"发生错误: {e}")

if __name__ == "__main__":
    main()